package red.social;

import java.io.DataInputStream;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;

public class FotosAdapter extends BaseAdapter {

	int mGalleryItemBackground;
	private Context mContext;
	DataInputStream dos;

	private List<Bitmap> mListaIds = new ArrayList<Bitmap>();
	private List<String> mListaNombres = new ArrayList<String>();

	public FotosAdapter(Context c,int idusuario) {

		mContext = c;
		TypedArray a = mContext
				.obtainStyledAttributes(R.styleable.HelloGallery);
		mGalleryItemBackground = a.getResourceId(
				R.styleable.HelloGallery_android_galleryItemBackground, 0);
		a.recycle();

		// Hago la consulta

		int x1 = 0;

		String ip = c.getResources().getString(R.string.ip);
		String servletURL = "http://"+ip+":8080/Modulo10-war/ServletFotos?idusuario="+idusuario;
		
		try {
			URL ob = new URL(servletURL);

			URLConnection conn = ob.openConnection();
			conn.setDoInput(true);

			InputStream in = conn.getInputStream();
			ObjectInputStream dos = new ObjectInputStream(in);

			int numFotos = dos.readInt();

			int x;

			while (x1 < numFotos) {

				// Lo que manda el Servlet

				System.out.println("RECIBO LA FOTO" + x1);

				if (x1 > 0) {
					ob = new URL(servletURL + "&numFotos=" + x1);
					conn = ob.openConnection();
					conn.setDoInput(true);
					in = conn.getInputStream();

					dos = new ObjectInputStream(in);
				}

				x1++;
				mListaNombres.add((String) dos.readObject());
				mListaIds.add(BitmapFactory.decodeStream(in));

				in.close();
				dos.close();
			}

		} catch (Exception e) {
			System.out.println(e.toString());
		}
	}

	public int getCount() {

		return mListaIds.size();
	}

	public Object getItem(int position) {
		return position;
	}

	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		ImageView i = new ImageView(mContext);

		i.setImageBitmap(mListaIds.get(position));

		i.setLayoutParams(new Gallery.LayoutParams(200, 200));
		i.setScaleType(ImageView.ScaleType.FIT_XY);
		i.setBackgroundResource(mGalleryItemBackground);

		return i;
	}

	public String getNombre(int positions) {
		return mListaNombres.get(positions);
	}

}
